package cn.codeforfun.initialization.thread;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.PreDestroy;
import java.util.concurrent.*;

/**
 * 线程服务
 *
 * @author wangbin
 */
@Service
public class ThreadService {

    private ExecutorService pool;

    public ThreadService() {
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
                .setNameFormat("local-thread-pool-%d").build();
        pool = new ThreadPoolExecutor(1, 5,
                60L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
    }

    public void execute(Runnable runnable) {
        pool.execute(runnable);
    }

    @PreDestroy
    public void destroy() {
        pool.shutdown();
    }

}
